using System;
using System.IO;
using System.Text;

namespace ThalesHsmComms
{
	public class GenerateZPKMsg : WSMMsg
	{

		public static readonly String DELIMETER = ";"; 
		public static readonly String KEY_CHECK_BACKWARDS = "0";
		
		String exportKey;
		String keyUnderZmk;
		String keyUnderLmk;
		String checkDigits;

		public GenerateZPKMsg(string zmk, char zmkScheme = 'U')
			:base("IA")
		{
			this.exportKey = zmkScheme + zmk;
		}

		override protected void Encode()
		{
			StringBuilder data = new StringBuilder();
			
			try 
			{
				// pack command code
				data.Append(this.commandCode);
				
				// pack zmk pair
				//data.write("U".getBytes());
				data.Append(this.exportKey);
				
				// pack key length flag
				data.Append(DELIMETER);
				
				// pack zmk key scheme
				data.Append("X");
				
				// pack lmk key scheme
				data.Append("U");
				
				// pack key chack mode
				data.Append(KEY_CHECK_BACKWARDS);
				
				
				this.requestData = ASCIIEncoding.ASCII.GetBytes(data.ToString());
				
			} catch (IOException ex) {
				Console.WriteLine(ex);
			}
			
		}

		override protected void Decode()
		{
			this.GetNextBytesFromResponse(1); // Read Encryption Scheme;
			this.keyUnderZmk = this.GetNextBytesFromResponse(32);
			this.GetNextBytesFromResponse(1); // Read Encryption Scheme;
			this.keyUnderLmk = this.GetNextBytesFromResponse(32);
			
			this.checkDigits = this.GetNextBytesFromResponse(16);
		}
	}
}

